package butines.core.game;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import butines.core.GameSystem;

public class MessageDispatcher {

	private Set<Message>  queuedMessage = new TreeSet<Message>();
	private List<Message> delayedMessages = new ArrayList<Message>();
	
	public MessageDispatcher() {
	}
	
	public void dispatch(Enum<?> type, GameEntity sender, GameEntity receiver, float delay, Object ... args) {
		if (delay < 0) {
			delay = 0;
		}
		if (args == null) {
			args = new Object[0];
		}
		float dispatchTime = GameSystem.getFrameTime() + delay;		
		Message message = new Message(type, sender, receiver, dispatchTime, args);
		if (delay <= 0) {
			discharge(message);
		} else {
			queuedMessage.add(message);
		}
	}
	
	private void discharge(Message message) {
		message.getReceiver().handleMessage(message);
	}
	
	private void findDelayedMessages() {
		float frameTime = GameSystem.getFrameTime();
		Iterator<Message> i = queuedMessage.iterator();
		while (i.hasNext()) {
			Message message = i.next();
			if (frameTime >= message.getDispatchTime()) {
				delayedMessages.add(message);
				i.remove();
			}
		}
	}
	
	public void dispatchDelayedMessages() {
		findDelayedMessages();
		
		for (Message message: delayedMessages) {
			discharge(message);
		}
		
		delayedMessages.clear();
	}
	
}
